import { NgModule, Optional, SkipSelf, ModuleWithProviders } from '@angular/core';
import { throwIfAlreadyLoaded } from './module-import-guard';
import { environment } from '@env/environment';

import { AuthModule } from './auth/auth.module';

import { AuthConfig } from './config/auth.config';

import { I18NService } from './i18n/i18n.service';
import { HttpServer } from './net/http-server';
import { ReturnMessage } from './net/return-message';
import { SystemService } from './system/system.service';
import { SystemUserService } from './system/system-user.service';

export function authConfig(): AuthConfig {
  return Object.assign(new AuthConfig(), <AuthConfig>{
    token_domain: environment.cookie.doMain,
    token_path: environment.cookie.path,
    login_url: '/passport/login',
    ignores: [/\/login/, /assets\//, /passport\//, /base\/login/, /base\/verify/, /fileUpload\//, /aliyuncs.com/],
    // header发送token
    token_send_key: 'Authorization',
    token_send_template: 'token ${token}',
    // cookie发送token
    // token_send_place: 'cookie',
    // store_key: Constant.COOKIE_KEY
  });
}

@NgModule({
  imports: [
    AuthModule.forRoot()
  ],
  providers: [
    I18NService,
    HttpServer,
    ReturnMessage,
    SystemService,
    SystemUserService
  ]
})
export class CoreModule {
  constructor(
    @Optional()
    @SkipSelf()
    parentModule: CoreModule,
  ) {
    throwIfAlreadyLoaded(parentModule, 'CoreModule');
  }

  static forRoot(): ModuleWithProviders {
    return {
      ngModule: CoreModule,
      providers: [
        {
          provide: AuthConfig,
          useClass: authConfig
        }
      ]
    };
  }
}
